package router

import (
	"github.com/gin-gonic/gin"
	"github.com/juexin/gin-base/internal/config"
	"github.com/juexin/gin-base/internal/handler"
	"github.com/juexin/gin-base/internal/middleware"
	"github.com/juexin/gin-base/internal/service"
	"gorm.io/gorm"
)

func Setup(db *gorm.DB, cfg *config.Config) *gin.Engine {
	// 设置 gin 模式
	gin.SetMode(cfg.Server.Mode)

	r := gin.New()

	// 全局中间件
	r.Use(middleware.Logger())
	r.Use(gin.Recovery())
	r.Use(middleware.CORS())

	// 初始化Repository
	// userRepo := repository.NewUserRepository(db) // 暂时未使用

	// 初始化Service
	smsService := service.NewSMSService(cfg)
	captchaService := service.NewCaptchaService(cfg, smsService.GetRedisPool())
	smsService.SetCaptchaService(captchaService)
	authService := service.NewAuthService(db, cfg, smsService)

	// 初始化Handler
	authHandler := handler.NewAuthHandler(authService)
	healthHandler := handler.NewHealthHandler()
	smsHandler := handler.NewSMSHandler(smsService)
	captchaHandler := handler.NewCaptchaHandler(captchaService)

	// 健康检查
	r.GET("/health", healthHandler.Check)

	// API 路由组
	api := r.Group("/api/v1")
	{
		// 认证相关（无需登录）
		auth := api.Group("/auth")
		{
			auth.POST("/login", authHandler.Login) // 登录（支持密码和短信验证码）
		}

		// 短信验证码相关（无需登录）
		sms := api.Group("/sms")
		{
			sms.POST("/send", smsHandler.SendVerificationCode) // 发送验证码
			sms.POST("/verify", smsHandler.VerifyCode)         // 验证验证码
		}

		// 图形验证码相关（无需登录）
		captcha := api.Group("/captcha")
		{
			captcha.GET("/generate", captchaHandler.GenerateCaptcha) // 生成图形验证码
			captcha.POST("/verify", captchaHandler.VerifyCaptcha)    // 验证图形验证码
		}

		// 需要认证的路由
		authorized := api.Group("")
		authorized.Use(middleware.JWT(cfg))
		{
			// 用户相关
			authorized.GET("/user/info", authHandler.GetUserInfo)
			authorized.POST("/auth/set-password", authHandler.SetPassword) // 设置密码（需要登录）
		}
	}

	return r
}
